package ru.diamond.home;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;

public class ClientSocket
{
	private Socket client;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	private boolean isOn = true;
	public ClientSocket(Socket client)
	{
		this.client = client;
		try
		{
			ois = new ObjectInputStream(client.getInputStream());
			oos = new ObjectOutputStream (client.getOutputStream());
		}
		catch(IOException ex)
		{
			isOn = false;
		}
		
		new Thread(new ClientListener()).start();
	}
	
	public void stopClient()
	{
		isOn = false;
	}
	
	private class ClientListener implements Runnable
	{
		@Override
		public void run() 
		{
			while (isOn)
			{
				try
				{
					Message mess  = (Message) ois.readObject();
					System.out.println(Server.sdf.format(new Date()) + "\t" + mess.fromName+ ":\t" + mess.message);
					
					mess = new Message("Data accepted", "Server");
					oos.writeObject(mess);
					oos.flush();
				}
				catch(Exception ex)
				{
					isOn = false;
					System.err.print(ex);
				}
			}
			
			try {
				client.close();
				ois.close();
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		
	
}
